if '__file__' in globals():
    import sys, os
    sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import numpy as np
from dezero import Variable
import dezero.functions as F

# 数据集
np.random.seed(0)
x = np.random.rand(100, 1)
y = np.sin(2 * np.pi * x) + np.random.rand(100, 1)

# 1 权重的初始化
I, H, O = 1, 10, 1
W1 = Variable(0.01 * np.random.randn(I, H))
b1 = Variable(np.zeros(H))
W2 = Variable(0.01 * np.random.randn(H, O))
b2 = Variable(np.zeros(O))

def predict(x):
    y = F.linear_simple(x, W1, b1)
    y = F.sigmoid_simple(y)
    y = F.linear_simple(y, W2, b2)
    return y

lr = 0.02
iters = 10000

for i in range(iters):
    y_pred = predict(x)
    loss = F.mean_squared_error(y, y_pred)

    W1.cleargrad()
    b1.cleargrad()
    W2.cleargrad()
    b2.cleargrad()
    loss.backward()

    W1.data -= lr * W1.grad.data
    b1.data -= lr * b1.grad.data
    W2.data -= lr * W2.grad.data
    b2.data -= lr * b2.grad.data

    if i % 1000 == 0:
        print(loss)


import matplotlib.pyplot as plt

# 排序x值以便绘制平滑曲线
x_sorted = np.sort(x, axis=0)
y_true_sorted = np.sin(2 * np.pi * x_sorted)  # 无噪声的真实值
y_pred_sorted = predict(x_sorted).data  # 模型预测值

plt.figure(figsize=(10, 6))
plt.scatter(x, y, label='Training data (with noise)', color='blue', alpha=0.5)
plt.plot(x_sorted, y_true_sorted, label='True function (sin(2πx))', color='green', linewidth=2)
plt.plot(x_sorted, y_pred_sorted, label='Model prediction', color='red', linewidth=2)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Comparison of True Function and Model Prediction')
plt.legend()
plt.grid(True)
plt.show()